extends Node2D

var changing = false
var volume = 1
var next = null
var music
const VOL_STEP = 0.05
var muted = false
var has_muted = false

# Called when the node enters the scene tree for the first time.
func _ready():
	music = $Music


# Called every frame. 'delta' is the elapsed time since the previous frame.
func _process(delta):
	if (!Input.is_action_pressed("mute")):
		has_muted = false
	elif (not has_muted and Input.is_action_pressed("mute")):
		has_muted = true
		if (muted):
			AudioServer.set_bus_volume_db(1, linear_to_db(volume))
			AudioServer.set_bus_volume_db(2, linear_to_db(volume))
		else:
			AudioServer.set_bus_volume_db(1, linear_to_db(0))
			AudioServer.set_bus_volume_db(2, linear_to_db(0))
		muted = not muted
	if (changing and volume > 0):
		volume -= VOL_STEP
		if (not muted):
			AudioServer.set_bus_volume_db(1, linear_to_db(volume))
	elif (changing):
		changing = false
		music.stream = next
		music.play()
		next = null
		volume = 1
		if (not muted):
			AudioServer.set_bus_volume_db(1, linear_to_db(volume))
	if (not music.is_playing() and not changing):
		music.play()

func play_sfx(name, unique=false):
	if (unique):
		get_node("Effect/"+name).play()
	else:
		var sfx = get_node("Effect/"+name).duplicate()
		get_node("Effect").add_child(sfx)
		sfx.play()
		sfx.finished.connect(remove_sfx.bind(sfx))

func remove_sfx(sfx):	
	sfx.queue_free()
	

func change_song(song):
	if (not changing):
		next = load(song)
		changing = true
